import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/util/auth'
import { doLoginApi } from '@/service/login'
import { getRoutesApi, getUserInfoApi } from '@/service/user'
import { constantRoutes } from '/src/router/index.js'

/**
 * 格式化后端返回的路由数据
 * @param routes 后端返回的路由数据
 */
function formatRoutes(routes) {
  return routes.map(route => {
    const formattedRoute = {
      path: route.path,
      name: route.name,
      meta: {
        title: route.title,
        icon: route.icon,
        roles: route.roles,
        hidden: route.hidden,
        table: route.table
      },
      component: loadComponent(route.component)
    }

    if (route.children && route.children.length) {
      formattedRoute.children = formatRoutes(route.children)
    }

    return formattedRoute
  })
}

/**
 * 动态加载组件
 * @param component 组件路径
 */
function loadComponent(component) {
  // 处理布局组件
  if (component === 'Layout') {
    return () => import('@/layout/index.vue')
  }
  // 处理其他组件
  return () => import(`@/pages/${component}.vue`)
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    realname: '',
    nickname: '',
    avatar: '',
    roles: [],
    routes: []
  }),
  
  actions: {
    // 登录
    async login(userInfo) {
      const { username, password, uuid, verify } = userInfo
      try {
        const { code, data, msg } = await doLoginApi({ username: username.trim(), password, uuid, verify })
        if (code === 200) {
          setToken(data.token)
          this.token = data.token
        } else {
          throw new Error(msg)
        }
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async getInfo() {
      try {
        const { data } = await getUserInfoApi()
        const { roles, user } = data

        // roles必须是非空数组
        // if (!roles || roles.length <= 0) {
        //   throw new Error('getInfo: roles must be a non-null array!')
        // }

        this.roles = roles
        this.realname = user.realname
        this.avatar = user.avatar
        // user 写入 localStorage
        localStorage.setItem('user', JSON.stringify(user))
        return { roles }
      } catch (error) {
        throw error
      }
    },

    // 从接口获取并生成路由
    async generateRoutes() {
      try {
        // 从接口获取路由数据
        const { data } = await getRoutesApi()
        // 格式化路由数据
        const asyncRoutes = formatRoutes(data)
        // 合并静态路由和动态路由
        this.routes = constantRoutes.concat(asyncRoutes)
        return asyncRoutes
      } catch (error) {
        throw error
      }
    },

    // 重置Token
    async resetToken() {
      removeToken()
      this.token = ''
      this.roles = []
    },

    // 登出
    async logout() {
      await this.resetToken()
      // 重置路由
      location.reload()
    }
  }
})